import {Component, ViewEncapsulation, ViewChild, Input,Output, EventEmitter} from '@angular/core';
import {IdeaService} from '../../../services/app.idea';
import {BaThemeSpinner}  from '../../../theme/services';
import {Modal} from 'ngx-modal';
import {cardIdea} from './component/cardIdea/cardIdea.component';
import {viewCardIdeaDetail} from './component/viewCardIdeaDetail/viewCardIdeaDetail.component';
import {UserProfile} from './../profile/profile.component';
import {Utility} from '../../../services/app.utility';
import {Router}  from '@angular/router';
import {UserService} from '../../../services/app.user';
//import {NgxMasonryComponent} from 'ngx-masonry';
declare let toastr:any;
declare let $:any;

@Component({
    selector: 'idea',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./idea.scss'],
    templateUrl: './idea.html'
})
export class Ideas {
    @Input()
    totalIdeas;
    @ViewChild('cardidea')
    public idea:cardIdea;
    @ViewChild('viewCardIdeaDetail')
    public viewDetailChild:viewCardIdeaDetail;
    @ViewChild('ViewDetailIdeaModel')
    public viewDetailIdeaModel:Modal;
    @ViewChild('abuseModal')
    public abuseModal:Modal;
    @ViewChild('UserModal')
    public userModal:Modal;
    // @ViewChild('myMasonry')
    // private myMasonry:NgxMasonryComponent;
    @ViewChild(UserProfile)
    public userprofile:UserProfile;

    public versioning: boolean;

  @Output()
  deleteIdeaNotify:EventEmitter<any> = new EventEmitter();

  public allIdeas:any;
    public showModal:boolean;
    public commentListOfIdea:any;
    u:string;
    public userModalClose:any;
    public fromDate:any;
    public toDate:any;
    public Ideas_Page:any;
    public TotalIdeas:any;
    public showMoreIdeaButton:boolean;
    public noMoreContent:any;
    public viewDetailIdea:any;
    public TotalIdea:any;
    public abuseIdea:any;

    constructor(private spinner:BaThemeSpinner, private router:Router, public utility:Utility, private ideaService:IdeaService, private userService:UserService) {
        this.showModal = false;
        this.userModalClose = false;
        this.commentListOfIdea = {
            skipCommentsItem: 0,
            commentsPerPage: 6,
        };
        this.fromDate = utility.getDatewithoutTimstamp(utility.getXMonthsAgoDate(new Date(), 180));
        this.toDate = utility.getDatewithoutTimstamp(new Date());
        this.Ideas_Page = {
            skipItem: 0,
            itemsperPage: 6,
            sortParameter: 'createdAt',
            sortOrder: 'descending',
            sortByTitle: '',
            sortByAuthor: '',
            sortByTags: [],
            toDate: this.toDate,
            fromDate: this.fromDate

        }

        this.userService.getuserInfo().subscribe(
            data => this.userInfoSuccess(data),
            error => {
            }
        );

    };

    //Function for fetching List of Ideas
    public ideaLists() {
        this.spinner.showProgress();
        this.Ideas_Page.toDate = this.toDate;
        this.Ideas_Page.fromDate = this.fromDate;
        this.ideaService.ideaList(this.Ideas_Page).subscribe(
            data => this.fetchListOfIdeasuccess(data),
            error => this.fail(error)
        );
    }

    public fetchListOfIdeasuccess(result) {
        for (let x = 0; x < result.ideaList.length; x++) {
            if (result.ideaList[x].citationArray !== undefined) {
                for (let y = 0; y < result.ideaList[x].citationArray.length; y++) {
                    result.ideaList[x].content = result.ideaList[x].content.replace(result.ideaList[x].citationArray[y], '<span class="keywordColor">' + result.ideaList[x].citationArray[y] + '</span>');
                }
            }
        }
        this.spinner.hideProgress();

        if (this.Ideas_Page.skipItem != 0) {
            let setData = this.TotalIdeas;
            setData.ideaList = setData.ideaList.concat(result.ideaList);
            this.TotalIdeas = null;
            this.TotalIdeas = setData;
        }
        else {
            this.TotalIdeas = result;
        }
        this.setIdeasInMasonry(this.TotalIdeas);
        if ((result.ideaCount - this.Ideas_Page.skipItem) > this.Ideas_Page.itemsperPage) {
            this.showMoreIdeaButton = true;
        }
        else {
            this.showMoreIdeaButton = false;
        }
        this.noMoreContent = (result.ideaCount > 0) ? false : true;
    }

    public fail(error) {
        this.spinner.hideProgress();
    }

    // get Comments
    public getIdeaComments(evt) {
        if (evt[0] !== undefined) {
            evt = evt[0];
        }
        let cardData = {
            'ideaId': evt._id,
            'skipItem': this.commentListOfIdea.skipCommentsItem,
            'itemsperPage': this.commentListOfIdea.commentsPerPage,
            'sortParameter': 'createdAt',
            'sortOrder': 'descending'
        };
        this.ideaService.getcardComment(cardData).subscribe(
            data => this.getcommentsuccess(data, evt),
            error => this.getcommentfail(error)
        );

    }

    public getcommentsuccess(data, evt) {
        this.spinner.hideProgress();
        let ModalData = evt;
        if (ModalData[0]) {
            ModalData[0].data = data;
            this.viewDetailIdea = ModalData[0];
        } else {
            ModalData.data = data;
            this.viewDetailIdea = ModalData;
        }
        this.viewDetailIdeaModel.open();
    }

    public getcommentfail(data) {
        this.spinner.hideProgress();
    }

    public setIdeasInMasonry(allIdea) {
        this.allIdeas = allIdea;
        this.TotalIdea = allIdea.ideaList;
    }
  deleteIdea(){
    // this.showModal = false;
    // this.userModalClose = false;
    // this.commentListOfIdea = {
    //   skipCommentsItem: 0,
    //   commentsPerPage: 6,
    // };
    // this.fromDate = this.utility.getDatewithoutTimstamp(this.utility.getXMonthsAgoDate(new Date(), 180));
    // this.toDate = this.utility.getDatewithoutTimstamp(new Date());
    // this.Ideas_Page = {
    //   skipItem: 0,
    //   itemsperPage: 6,
    //   sortParameter: 'createdAt',
    //   sortOrder: 'descending',
    //   sortByTitle: '',
    //   sortByAuthor: '',
    //   sortByTags: [],
    //   toDate: this.toDate,
    //   fromDate: this.fromDate
    // }
    this.deleteIdeaNotify.emit({});
  }

    // Do something with the notification (evt) sent by the child!
    getNotification(idea) {
        this.getIdeaComments(idea);
    }

    notifyParenttoAbuse(idea) {
        this.abuseIdea = idea;
        this.abuseModal.open();
    }

    getNotificationModal(idea) {
        this.abuseIdea = idea;
        this.abuseModal.open();


    }

    closeUserrModel(data) {
        if (this.userModal.isOpened) {
            // this.userModalClose = true;
            this.userModal.close();
        }
        this.getIdeaIdForAbuse(data.idea, data.user);
    }

    public getIdeaIdForAbuse(idea, user) {
        let input = {
            ideaId: idea,
            userId: user
        };

        this.ideaService.getIdeaIdForAbuse(input).subscribe(
            data => this.getIdeaByIdSucess(data),
            error => this.getIdeaByIdFailure(error));
    }

    private getIdeaByIdSucess(stats) {
        this.spinner.hideProgress();
        this.getIdeaComments(stats);
    }

    private getIdeaByIdFailure(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);
    }

    getNotificationAbuseModal(evt) {
        this.abuseIdea = null;
        this.abuseModal.close();
    }

    notifyParenttoProfileCard(evt) {
        this.utility.clickFromProfile = false;
        this.userprofile.hideEdit();
        this.userprofile.resetProile();
        this.userprofile.getUserProfileData(evt.user, undefined, undefined);
        this.userModal.open();
    }

    notifyParenttoProfileModal(evt) {
        this.utility.clickFromProfile = false;
        this.userprofile.hideEdit();
        this.userprofile.resetProile();
        this.userprofile.getUserProfileData(evt.user, undefined, undefined);
        this.userModal.open();
    }


    public userInfoSuccess(data) {
        console.log("cardIdea");

        if (data.version === 'Version_1') {
            this.versioning = false;
        } else if (data.version === 'Version_2') {
            this.versioning = false;
        } else if (data.version === 'Version_4') {
            this.versioning = false;
        } else if (data.version === 'Version_6') {
            this.versioning = false;
        } else {
            this.versioning = true;
        }
    }
}
